package com.wn.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wn.common.pojo.*;
import com.wn.common.util.Const;
import com.wn.common.util.JWTUtil;
import com.wn.mapper.AppointmentMapper;
import io.jsonwebtoken.Jwt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class AppointmentService {

        @Autowired
        private AppointmentMapper appointmentMapper;
        @Autowired
        private CityService cityService;
        @Autowired
        private DestinationService destinationService;


    /**
     * 添加预约
     * @param appointment
     * @return
     */
    public Rsp insert(Appointment appointment){

         return  appointmentMapper.insert(appointment) == 1 ?
                 new Rsp().success("添加成功") : new Rsp().fail().msg("添加失败");
      }

    /**
     * 修改预约
     * @param appointment
     * @return
     */
      public Rsp update(Appointment appointment){

        return appointmentMapper.updateByPrimaryKeySelective(appointment) == 1 ?
                new Rsp().success("修改成功") : new Rsp().fail().msg("修改失败");
       }

    /**
     * 根据条件查询
     * @param pageParam
     * @return
     */

      public Rsp queryByCondition(PageParam<Appointment> pageParam){

              //分页
              PageHelper.startPage(pageParam.getPageNum(),pageParam.getPageSize());
              List<Appointment> appointmentList = appointmentMapper.selectByCondition(pageParam.getModel());
              PageInfo<Appointment> pageInfo = new PageInfo<Appointment>(appointmentList);
              for(Appointment a:appointmentList){
                  System.out.println("------"+a+"--------");
              }
          if(pageInfo.getList()!=null)
              return Rsp.success(pageInfo).msg("查询成功!");
          else
              return Rsp.fail().msg("查询失败！");
          }


      public Rsp delete(Integer id){

          return appointmentMapper.deleteByPrimaryKey(id)== 1 ?
                  new Rsp().success("删除成功") : new Rsp().fail().msg("删除失败");
      }

      public Rsp queryById(Integer id){
          Appointment appointment = appointmentMapper.selectByPrimaryKey(id);
          return  appointment== null ?
                  new Rsp().fail().msg("查询失败")  : new Rsp().success(appointment);
      }

    /*添加预约订单*/
    public Rsp createAppointment(Appointment appointment,User user) {
        //做数据校验
        log.info("需要校验的数据为：{}",appointment);
        if(appointment == null){
            return new Rsp().fail().msg("不能提交空订单！");
        }else if(appointment.getFromCityIds() == null ){
            return new Rsp().fail().msg("请选择预计出发的城市！");
        }else if(appointment.getDestinationIds() == null){
            return new Rsp().fail().msg("请选择目的地！");
        }else if(StringUtils.isEmpty(appointment.getContactName())){
            return new Rsp().fail().msg("请填写联系人！");
        }else if(StringUtils.isEmpty(appointment.getContactPhone())){
            return new Rsp().fail().msg("请填写联系人号码！");
        }
//        if(appointment.getChildrenNum()==0){
//            appointment
//        }
        //通过验证之后执行添加表操作
        appointment.setUserId(user.getUserId());
        appointment.setUserName(user.getUserName());
        //出发地
        Integer cityId = appointment.getFromCityIds().get(appointment.getFromCityIds().size() - 1);
        City cityRes = (City) cityService.getCityByRegionCode(cityId).getContent();
        appointment.setFromCity(cityRes.getSimplename());
        //目的地
        Integer DestinationId = appointment.getDestinationIds().get(appointment.getDestinationIds().size()-1);
        Destination  destination =(Destination) destinationService.getById(DestinationId).getContent();
        appointment.setDestination(destination.getAreaname());


        String str = "";
        for(String app: appointment.getTypes()){
            str =str+ app+",";
        }
        appointment.setType(str);
        //生成订单编号
        Integer orderId= UUID.randomUUID().toString().hashCode();
        orderId = orderId < 0 ? -orderId : orderId; //String.hashCode() 值会为空
        appointment.setOrderNumber(orderId);
        //默认状态为0
        appointment.setStatus(0);
        appointment.setIsDeleted("0");
        //给定默认方案
        appointment.setSchemeId(7);

        return new Rsp().success(appointmentMapper.insertSelective(appointment));
    }

    /*根据订单编号查询*/
    public Rsp queryByOrderNumber(Integer orderNumber) {
        log.info("查询的订单编号是:{}",orderNumber);
        Appointment appointment = appointmentMapper.getByOrderNumber(orderNumber);

        return new Rsp().success(appointment);
    }
    /*用户进入个人中心查看所有预约订单*/
    public Rsp getAppointmentDetailByUserInfo(String token) throws Exception {
        //解析token拿到userid
        User user = JWTUtil.parserToken(token, Const.PUBLIC_KEY);
        //根据userid拿到用户所有的预约订单
        List<Appointment> appointments = appointmentMapper.selectAllAppointmentByUserId(user.getUserId());
        appointments.forEach(e->{
            e.setNumber(e.getChildrenNum()+e.getManNum());

        });

        return new Rsp().success(appointments);
    }
    /*管理员修改预约订单状态至待付款  根据订单编号*/
    public Rsp changeStatusToPay(Appointment appointment) {

        return  appointmentMapper.updateStatusToPay(appointment.getOrderNumber(),appointment.getResPrice())==1?
                new Rsp().success(null).msg("更新成功") : new Rsp().fail().msg("更新失败");
    }
    /*支付成功更新预约单状态*/
    public void changeStatusToPayOff(String orderPaynumber) {
        //查询是否存在该预约单
        Appointment appointment = appointmentMapper.selectByOrderNumber(Integer.parseInt(orderPaynumber));
        if(StringUtils.isEmpty(appointment)){
            return;
        }else{
            appointmentMapper.changeStatusToPayOffByOrderNumber(Integer.parseInt(orderPaynumber));
        }
    }
}
